package com.stylefeng.guns.rest.modular;

import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Selectable;

import java.util.ArrayList;
import java.util.List;

public class GithubRepoPageProcessor implements PageProcessor {

    // 部分一：抓取网站的相关配置，包括编码、抓取间隔、重试次数等
    private Site site = Site.me().setRetryTimes(3).setSleepTime(1000);

    //public static final String list = "http://www.hsshy.cn/";
    public static final String list = "http://fz.58.com/zufang/";

    @Override
    // process是定制爬虫逻辑的核心接口，在这里编写抽取逻辑
    public void process(Page page) {
        List<String> urls = new ArrayList<>();/*page.getHtml().css("div.pager").links().all();*/

        urls.add("http://fz.58.com/zufang/");
        for(int i=1;i<=70;i++){
            urls.add("http://fz.58.com/zufang/pn"+i+"/");
        }

        page.addTargetRequests(urls);

        if (page.getUrl().regex(list).match()) {
            List<Selectable> list=page.getHtml().xpath("//ul[@class='listUl']/li").nodes();
            System.out.println("长度："+list.size());
            for (Selectable s : list) {
                String title=s.xpath("//div[@class='des']/h2/a/text()").toString();
                page.putField("title:"+title,title);
            }
        }
    }

    @Override
    public Site getSite() {
        return site;
    }

    public static void main(String[] args) {

        Spider.create(new GithubRepoPageProcessor())
                //从"https://github.com/code4craft"开始抓
                .addUrl("http://fz.58.com/zufang/")
                //开启5个线程抓取
                .thread(5)
                //启动爬虫
                .addPipeline(new NewsPipeline())
                .run();
    }
}